package com.huazai.juc.cec.thread.august.nineteen;

import com.huazai.juc.utils.SleepUtil;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @author Seon
 * @date 2022/8/19 1:18
 * 笨栗子来说明不在意修改次数，只在意是否被修改过。浅拷贝问题
 */
@Slf4j
public class AtomicMarkableReferenceStudy {

    public static void main(String[] args) {
        GarbageBag garbageBag = new GarbageBag("装满了垃圾");
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(garbageBag, true);

        log.info("start...");
        GarbageBag prev = ref.getReference();
        log.info(prev.toString());


        /*
        Supplier<String> arraySupplier;
        Function<String, Integer> lengthFun;
        BiConsumer<String, Integer> putConsumer;
        Consumer<String> printConsumer;
         */


        new Thread(() -> {
            log.info("start...");
            garbageBag.setDesc("垃圾已经被保洁阿姨倒干净了。。。");
            boolean result = ref.compareAndSet(garbageBag, garbageBag, true, false);
            log.info(garbageBag.toString());
        }, "保洁阿姨").start();

        SleepUtil.MySleep(1);
        log.info("要换一只新的垃圾袋吗");
        boolean result = ref.compareAndSet(prev, new GarbageBag("一只空的新的垃圾袋"), true, false);
        log.info("换了吗？" + result);
        log.info(ref.getReference().toString());

    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class GarbageBag {
    String desc;

    @Override
    public String toString() {
        return super.toString() + " " + desc;
    }
}
